package goutil

import (
	"errors"
	"reflect"
	"sync"
)

func DelSliceAt(s []any, itm any) bool {
	b := false
	if s != nil {
		for i := 0; i < len(s); i++ {
			if itm == s[i] {
				s = append(s[:i], s[i+1:])
				b = true
				break
			}
		}
	}
	return b
}

// 判断obj是否在target中，target支持的类型 arrary, slice, map
func Contain(obj interface{}, target interface{}) (bool, error) {
	targetValue := reflect.ValueOf(target)
	switch reflect.TypeOf(target).Kind() {
	case reflect.Slice, reflect.Array:
		for i := 0; i < targetValue.Len(); i++ {
			if targetValue.Index(i).Interface() == obj {
				return true, nil
			}
		}
	case reflect.Map:
		if targetValue.MapIndex(reflect.ValueOf(obj)).IsValid() {
			return true, nil
		}
	}

	return false, errors.New("not in array")
}

// 将 sync.Map 转变为 Map
func SyncMap2Map(source *sync.Map) (rv map[string]interface{}) {
	rv = make(map[string]interface{})
	source.Range(func(k, v interface{}) bool {
		rv[k.(string)] = v
		return true
	})
	return
}
